package com.dc.system.service.impl;

import com.dc.base.exception.BusinessException;
import com.dc.common.constants.ConstantsCommon;
import com.dc.common.model.BaseModel;
import com.dc.system.mapper.SysDeptMapper;
import com.dc.system.mapper.SysOrganMapper;
import com.dc.system.mapper.UserMapper;
import com.dc.system.model.*;
import com.dc.system.service.SysDeptService;
import com.dc.common.verification.RegexUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: SysDeptServiceImpl
 * @Author: ChenXueLi
 * @Date: 2018-05-05 9:22
 */
@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SysOrganMapper sysOrganMapper;

    /**
     * 添加一个部门
     * @param sysDept
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel addSysDept(SysDept sysDept, SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        // 获取用户
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        // 验证数据是否完整
        if(sysDept.getName() == null || "".equals(sysDept.getName())) {
            throw new BusinessException(-102, "部门名称不能为空");
        }
        // 保证上级部门id存在除非不设置上级部门
        if(sysDept.getFk_parent_id() != 0) {
            // 查询出是否存在该部门
            boolean hasDept = sysDeptMapper.getSysDeptById(sysDept.getFk_parent_id()) != null;
            if(!hasDept) {
                throw new BusinessException(-103, "上级部门查询失败");
            }
        }
        if(sysDept.getFk_header_id() != 0) {
            // 查询用户表
            boolean hasUser = true;
            if(!hasUser) {
                throw new BusinessException(-104, "负责人查询失败");
            }
        }
        if(sysDept.getFk_contacts_id() != 0) {
            // 查询用户表
            boolean hasUser = true;
            if(!hasUser) {
                throw new BusinessException(-105, "联系人查询失败");
            }
        }
        if(sysDept.getTelephone() == null || !RegexUtil.isTel(sysDept.getTelephone())) {
            throw new BusinessException(-106, "联系方式格式不正确");
        }
        if(sysDept.getAddress() == null || "".equals(sysDept.getAddress())) {
            throw new BusinessException(-107, "地址不能为空");
        }
        if(sysOrgan.getOrgan_id() != 0) {
            boolean hasSysOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id()) != null;
            if(!hasSysOrgan) {
                throw new BusinessException(-108, "单位查询失败");
            }
        }

        // 添加默认参数
        sysDept.setCreate_time(new Date());
        sysDept.setCreate_user_name(sysUser.getAccount());
        sysDept.setCreate_user_id(sysUser.getUser_id());
        sysDept.setUpdate_time(new Date());
        sysDept.setUpdate_user_name(sysUser.getAccount());
        sysDept.setUpdate_user_id(sysUser.getUser_id());
        sysDept.setIs_deleted(1);
        sysDept.setVersion(0);
        // 查询当前的数总数
        int currentRows = sysDeptMapper.getSysDeptsCount();
        // 当前排序号是在总数之后或者为0的情况下是在末尾直接追加
        if(sysDept.getOrder_code() > currentRows || sysDept.getOrder_code() == 0) {
            // 排在末尾
            sysDept.setOrder_code(currentRows + 1);
        }else {
            // 重新校验排序
            int tempEffectRows = sysDeptMapper.updateSysDeptOrderCodeIncreaseByOrderCode(sysDept);
        }

        int effectRows = sysDeptMapper.addSysDept(sysDept);
        if(effectRows != 1) {
            // 这里需要把顺序排回去
            sysDeptMapper.updateSysDeptOrderCodeDecreaseByOrderCode(sysDept);
            throw new BusinessException(-109, "系统错误，添加部门失败！");
        }
        baseModel.setCode(0);
        baseModel.setMessage("添加部门成功");
        // 更新部门数据
        sysDept = sysDeptMapper.getSysDeptById(sysDept.getDept_id());
        // 绑定单位
        if(sysOrgan.getOrgan_id() != 0) {
            // 添加绑定单位
            SysDeptOrgan sysDeptOrgan = new SysDeptOrgan();
            sysDeptOrgan.setFk_dept_id(sysDept.getDept_id());
            sysDeptOrgan.setFk_organ_id(sysOrgan.getOrgan_id());
            effectRows = sysDeptMapper.addSysDeptOrgan(sysDeptOrgan);
            if(effectRows != 1) {
                baseModel.setMessage("添加部门成功，但是绑定单位失败");
            }
        }
        baseModel.setData(sysDept);
        return baseModel;
    }

    /**
     * 根据部门id删除一个部门
     * @param sysDept
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel deleteSysDeptById(SysDept sysDept, BaseModel baseModel, HttpServletRequest request) throws Exception {
        // 获取用户
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        sysDept = sysDeptMapper.getSysDeptById(sysDept.getDept_id());
        if(sysDept == null){
            throw new BusinessException(-102, "获取部门失败！");
        }
        sysDept.setUpdate_time(new Date());
        sysDept.setUpdate_user_name(sysUser.getAccount());
        sysDept.setUpdate_user_id(sysUser.getUser_id());
        sysDept.setIs_deleted(0);
        int effectRows = sysDeptMapper.deleteSysDeptById(sysDept);

        if(effectRows != 1) {
            throw new BusinessException(-103, "系统错误，删除部门失败！");
        }

        // 删除相关的单位绑定
        effectRows = sysDeptMapper.deleteSysDeptOrgan(sysDept.getDept_id(), null);
        // 重整之后序号的部门
        effectRows = sysDeptMapper.updateSysDeptOrderCodeDecreaseByOrderCode(sysDept);

        baseModel.setCode(0);
        baseModel.setMessage("删除部门成功");
        baseModel.setData(sysDept);
        return baseModel;
    }

    /**
     * 根据部门id修改一个部门的信息
     * @param sysDept
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel updateSysDeptById(SysDept sysDept, SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        // 获取用户
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        if(sysDept.getDept_id() == sysDept.getFk_parent_id()) {
            throw new BusinessException(-102, "上级部门不能是自身");
        }
        // 获取到原来的部门数据判断排序是否有变化
        SysDept originalSysDept = sysDeptMapper.getSysDeptById(sysDept.getDept_id());
        if(originalSysDept == null) {
            throw new BusinessException(-103, "获取部门失败！");
        }
        // 验证数据是否完整
        if(sysDept.getName() == null || "".equals(sysDept.getName())) {
            throw new BusinessException(-104, "部门名称不能为空");
        }
        // 保证上级部门id存在除非不设置上级部门
        if(sysDept.getFk_parent_id() != 0) {
            // 查询出是否存在该部门
            boolean hasDept = sysDeptMapper.getSysDeptById(sysDept.getFk_parent_id()) != null;
            if(!hasDept) {
                throw new BusinessException(-105, "上级部门查询失败");
            }
        }
        if(sysDept.getFk_header_id() != 0) {
            // 查询用户表
            boolean hasUser = true;
            if(!hasUser) {
                throw new BusinessException(-106, "负责人查询失败");
            }
        }
        if(sysDept.getFk_contacts_id() != 0) {
            // 查询用户表
            boolean hasUser = true;
            if(!hasUser) {
                throw new BusinessException(-107, "联系人查询失败");
            }
        }
        if(sysDept.getTelephone() == null || !RegexUtil.isTel(sysDept.getTelephone())) {
            throw new BusinessException(-108, "联系方式格式不正确");
        }
        if(sysDept.getAddress() == null || "".equals(sysDept.getAddress())) {
            throw new BusinessException(-109, "地址不能为空");
        }
        // 修改绑定（一个部门对应一个单位）
        if(sysOrgan.getOrgan_id() != 0) {
            boolean hasSysOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id()) != null;
            if(!hasSysOrgan) {
                throw new BusinessException(-110, "单位查询失败");
            }
            // 获取之前的绑定
            List<SysOrgan> tempSysOrgans = sysOrganMapper.getSysOrganByDept(sysDept.getDept_id());
            // 默认只有一个单位（同时保证单位不为空）
            if(tempSysOrgans.size() > 0 && tempSysOrgans.get(0).getOrgan_id() == sysOrgan.getOrgan_id()) {
                // 之前绑定的与修改的相同，不用重新绑定
            }else {
                // 删除一次绑定（防止单位被删除，但是绑定未被删除）
                sysDeptMapper.deleteSysDeptOrgan(sysDept.getDept_id(), null);
                // 删除成功，重新绑定
                SysDeptOrgan sysDeptOrgan = new SysDeptOrgan();
                sysDeptOrgan.setFk_dept_id(sysDept.getDept_id());
                sysDeptOrgan.setFk_organ_id(sysOrgan.getOrgan_id());
                int effectRows = sysDeptMapper.addSysDeptOrgan(sysDeptOrgan);
                if(effectRows != 1) {
                    throw new BusinessException(-111, "系统错误，修改绑定单位失败");
                }
            }
        }

        // 重新排序
        if(originalSysDept.getOrder_code() != sysDept.getOrder_code()) {
            // 先将原数据的执行减1
            int tempEffectRows = sysDeptMapper.updateSysDeptOrderCodeDecreaseByOrderCode(originalSysDept);
            // 再将新数据的加1
            tempEffectRows = sysDeptMapper.updateSysDeptOrderCodeIncreaseByOrderCode(sysDept);
        }
        sysDept.setUpdate_time(new Date());
        sysDept.setUpdate_user_name(sysUser.getAccount());
        sysDept.setUpdate_user_id(sysUser.getUser_id());
        sysDept.setVersion(originalSysDept.getVersion());

        int effectRows = sysDeptMapper.updateSysDeptById(sysDept);
        if(effectRows != 1) {
            // 返回顺序
            sysDeptMapper.updateSysDeptOrderCodeDecreaseByOrderCode(sysDept);
            sysDeptMapper.updateSysDeptOrderCodeIncreaseByOrderCode(originalSysDept);
            throw new BusinessException(-112, "系统错误，修改部门失败！");
        }
        baseModel.setCode(0);
        baseModel.setMessage("修改部门成功");
        // 更新部门数据
        sysDept = sysDeptMapper.getSysDeptById(sysDept.getDept_id());
        baseModel.setData(sysDept);
        return baseModel;
    }

    /**
     * 分页查询所有部门
     * @param pageInfo
     * @param sysDept
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel getSysDepts(PageInfo<?> pageInfo, SysDept sysDept, SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        Map<String, Object> params = new HashMap<>();
        // 添加参数
        if(sysDept.getName() != null && !"".equals(sysDept.getName())) {
            params.put("name", sysDept.getName());
        }
        if(sysDept.getFk_parent_id() != 0 && !"".equals(sysDept.getFk_parent_id())) {
            params.put("fk_parent_id", sysDept.getFk_parent_id());
        }
        if(sysDept.getFk_header_id() != 0 && !"".equals(sysDept.getFk_header_id())) {
            params.put("fk_header_id", sysDept.getFk_header_id());
        }
        if(sysDept.getFk_header_id() != 0 && !"".equals(sysDept.getFk_header_id())) {
            params.put("fk_contacts_id", sysDept.getFk_header_id());
        }
        if(sysDept.getTelephone() != null && !"".equals(sysDept.getTelephone())) {
            params.put("telephone", sysDept.getTelephone());
        }
        if(sysDept.getFunctions() != null && !"".equals(sysDept.getFunctions())) {
            params.put("functions", sysDept.getFunctions());
        }
        if(sysDept.getOrder_code() != 0 && !"".equals(sysDept.getOrder_code())) {
            params.put("order_code", sysDept.getOrder_code());
        }
        if(sysDept.getAddress() != null && !"".equals(sysDept.getAddress())) {
            params.put("address", sysDept.getAddress());
        }
        if(sysDept.getMemo() != null && !"".equals(sysDept.getMemo())) {
            params.put("memo", sysDept.getMemo());
        }
        if(sysDept.getCreate_user_id() != 0 && !"".equals(sysDept.getCreate_user_id())) {
            params.put("create_user_id", sysDept.getCreate_user_id());
        }
        if(sysDept.getCreate_user_name() != null && !"".equals(sysDept.getCreate_user_name())) {
            params.put("create_user_name", sysDept.getCreate_user_name());
        }
        if(sysDept.getUpdate_user_id() != 0 && !"".equals(sysDept.getUpdate_user_id())) {
            params.put("update_user_id", sysDept.getUpdate_user_id());
        }
        if(sysDept.getUpdate_user_name() != null && !"".equals(sysDept.getUpdate_user_name())) {
            params.put("update_user_name", sysDept.getUpdate_user_name());
        }
        // 创建时间开始
        String create_time_start = request.getParameter("create_time_start");
        if(create_time_start != null && !"".equals(create_time_start)) {
            params.put("create_time_start", create_time_start);
        }
        // 创建时间结束
        String create_time_end = request.getParameter("create_time_end");
        if(create_time_end != null && !"".equals(create_time_end)) {
            params.put("create_time_end", create_time_end);
        }
        // 修改时间开始
        String update_time_start = request.getParameter("update_time_start");
        if(update_time_start != null && !"".equals(update_time_start)) {
            params.put("update_time_start", update_time_start);
        }
        // 修改时间结束
        String update_time_end = request.getParameter("update_time_end");
        if(update_time_end != null && !"".equals(update_time_end)) {
            params.put("update_time_end", update_time_end);
        }
        // 添加单位信息
        if(sysOrgan.getOrgan_id() != 0 && !"".equals(sysOrgan.getOrgan_id())) {
            params.put("organId", sysOrgan.getOrgan_id());
        }
        // 判断是否需要分页查询（默认为分页查询）
        String getByPage = request.getParameter("getByPage");
        if(getByPage != null && !"".equals(getByPage)) {
            // 只要有值就不是分页查询
            List<SysDept> sysDepts = sysDeptMapper.getSysDepts(params);
            baseModel.setData(sysDepts);
            baseModel.setMessage("查询成功");
        }else {
            int pageNum = pageInfo.getPageNum() <= 0 ? 0 : pageInfo.getPageNum();
            int pageSize = pageInfo.getPageSize() <= 0 ? 10 : pageInfo.getPageSize();
            // 分页插件,但是PageHelper必须在查询语句前，最好写在service实现层
            PageHelper.startPage(pageNum, pageSize);
            List<SysDept> sysDepts = sysDeptMapper.getSysDepts(params);
            // 通过pageHelper插件pageInfo封装，更加方便
            PageInfo<SysDept> resultSysDept = new PageInfo<SysDept>(sysDepts);
            baseModel.setData(resultSysDept);
            baseModel.setMessage("查询成功");
        }
        return baseModel;
    }

    /**
     * 向单位中添加部门（绑定）
     * @param sysDept
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel bindDeptAndOrgan(SysDept sysDept, SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        if(sysDept.getDept_id() != 0) {
            boolean hasDept = sysDeptMapper.getSysDeptById(sysDept.getDept_id()) != null;
            if(!hasDept) {
                throw new BusinessException(-102, "获取部门失败");
            }
        }
        if(sysOrgan.getOrgan_id() != 0) {
            boolean hasOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id()) != null;
            if(!hasOrgan) {
                throw new BusinessException(-103, "获取单位失败");
            }
        }
        // 查询是否绑定了已经
        List<SysDeptOrgan> sysDeptOrgans = sysDeptMapper.getSysDeptOrgans(sysDept.getDept_id(), sysOrgan.getOrgan_id());
        if(sysDeptOrgans.size() > 0) {
            baseModel.setCode(0);
            baseModel.setMessage("已经绑定了");
            return baseModel;
        }
        SysDeptOrgan sysDeptOrgan = new SysDeptOrgan();
        sysDeptOrgan.setFk_dept_id(sysDept.getDept_id());
        sysDeptOrgan.setFk_organ_id(sysOrgan.getOrgan_id());
        int effectRows = sysDeptMapper.addSysDeptOrgan(sysDeptOrgan);
        if(effectRows != 1) {
            throw new BusinessException(-104, "系统错误，绑定失败");
        }
        baseModel.setCode(0);
        baseModel.setMessage("绑定成功");
        return baseModel;
    }

    /**
     * 解绑
     * @param sysDept
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel deleteBindDeptAndOrgan(SysDept sysDept, SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        if(sysDept.getDept_id() != 0) {
            boolean hasDept = sysDeptMapper.getSysDeptById(sysDept.getDept_id()) != null;
            if(!hasDept) {
                throw new BusinessException(-102, "获取部门失败");
            }
        }
        if(sysOrgan.getOrgan_id() != 0) {
            boolean hasOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id()) != null;
            if(!hasOrgan) {
                throw new BusinessException(-103, "获取单位失败");
            }
        }
        // 查询是否绑定了已经
        List<SysDeptOrgan> sysDeptOrgans = sysDeptMapper.getSysDeptOrgans(sysDept.getDept_id(), sysOrgan.getOrgan_id());
        if(sysDeptOrgans.size() == 0) {
            baseModel.setCode(0);
            baseModel.setMessage("没有绑定过，操作失败");
            return baseModel;
        }
        int effectRows = sysDeptMapper.deleteSysDeptOrgan(sysDept.getDept_id(), sysOrgan.getOrgan_id());
        if(effectRows != 1) {
            throw new BusinessException(-104, "系统错误，解绑失败");
        }
        baseModel.setCode(0);
        baseModel.setMessage("解绑成功");
        return baseModel;
    }


}
